package com.study.example.study.extension.easyexcel.write;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.ReadConverterContext;
import com.alibaba.excel.converters.WriteConverterContext;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.google.common.collect.ImmutableMap;
import org.apache.commons.lang3.StringUtils;

import java.util.Map;

/**
 * 状态转换
 *
 * @author RenYuLiang
 */
public class EasyExcelWriteStatusConverter implements Converter<String> {

    /**
     * 初始化 Map 不可变
     */
    private static final Map<String, String> STATUS_MAP = ImmutableMap.<String, String>builder().put("1", "启用").put("2", "禁用").build();


    @Override
    public Class<?> supportJavaTypeKey() {
        // 对象属性类型
        return String.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        // CellData 属性类型
        return CellDataTypeEnum.STRING;
    }

    /**
     * 这里是读的时候会调用
     *
     * @param context ReadConverterContext
     * @return Integer
     */
    @Override
    public String convertToJavaData(ReadConverterContext<?> context) {
        // CellData 转对象属性
        String readCellValue = context.getReadCellData().getStringValue();
        if (StringUtils.isBlank(readCellValue)) {
            return null;
        }
        String status = null;
        for (Map.Entry<String, String> entry : STATUS_MAP.entrySet()) {
            if (readCellValue.equals(entry.getValue())) {
                status = entry.getKey();
            }
        }
        return status;
    }

    /**
     * 这里是写的时候会调用
     *
     * @param context WriteConverterContext
     */
    @Override
    public WriteCellData<?> convertToExcelData(WriteConverterContext<String> context) {
        // 对象属性转 CellData
        String cellValue = context.getValue();
        String cellValueStr = "异常";
        if (StringUtils.isNotBlank(cellValue)) {
            String value = STATUS_MAP.get(cellValue);
            if (StringUtils.isNotBlank(value)) {
                cellValueStr = value;
            }
        }
        return new WriteCellData<>(cellValueStr);
    }

}
